package com.sansi.bleFloodlight.fragment;

import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.my.httpapi.api.baseUtils.LogUtils;
import com.my.httpapi.api.baseUtils.Toast;
import com.my.httpapi.api.baseView.BaseFragment;

import com.sansi.bleFloodlight.R;
import com.sansi.bleFloodlight.adapter.HomeLightAdapter;
import com.sansi.bleFloodlight.ble.bleInterface.BleManageListener;
import com.sansi.bleFloodlight.ble.BleManageUtils;
import com.sansi.bleFloodlight.ble.bleInterface.IBleManage;
import com.sansi.bleFloodlight.db.TableDevice;
import com.sansi.bleFloodlight.http.Api;
import com.sansi.bleFloodlight.model.ChangeLightColorEvent;
import com.sansi.bleFloodlight.model.ChangeLightProgressEvent;
import com.sansi.bleFloodlight.model.DeviceConfigureResponse;
import com.sansi.bleFloodlight.model.HomeLightEvent;
import com.sansi.bleFloodlight.model.RemoveLightEvent;
import com.sansi.bleFloodlight.utils.RouterPath;
import com.sansi.bleFloodlight.view.SpaceHomeLightItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.util.List;

import static com.sansi.bleFloodlight.ble.BluetoothUtils.getBluetoothAdapter;

public class HomeLightFragment extends BaseFragment implements BleManageListener {

    private RecyclerView recyclerView;
    private HomeLightAdapter homeLightAdapter;
    private TextView btnAddLight;
    private IBleManage iBleManage;

    public static Fragment newInstance() {
        return new HomeLightFragment();
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        iBleManage = new BleManageUtils(getActivity(), this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        homeLightAdapter = new HomeLightAdapter(iBleManage);
        homeLightAdapter.setEmptyView(getEmptyView());
        recyclerView.setAdapter(homeLightAdapter);
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.dp_9);
        recyclerView.addItemDecoration(new SpaceHomeLightItemDecoration(spacingInPixels));
        btnAddLight.setOnClickListener(view -> RouterPath.gotoBleSearchPath());
        homeLightAdapter.setOnItemClickListener((adapter, view, position) -> {
            BluetoothDevice bluetoothDevice = homeLightAdapter.getData().get(position).getBluetoothDevice();
            RouterPath.gotoLightClosePathPath(bluetoothDevice
                    , homeLightAdapter.getData().get(position).getColor()
                    , homeLightAdapter.getData().get(position).getBrightProgress());
        });
        getFromDataBase();
        getHttp();
    }

    @Override
    protected int layout() {
        return R.layout.layout_fragment_home_light;
    }

    @Override
    protected void bindView(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
    }

    @Override
    protected void lazyLoad() {

    }

    @Override
    protected void lazyLoadOne() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private View getEmptyView() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_home_light_empty, null, false);
        btnAddLight = view.findViewById(R.id.btn_add_light);
        return view;
    }

    private void getFromDataBase() {
        List<TableDevice> listDevice = LitePal.findAll(TableDevice.class);
        for (int i = 0; i < listDevice.size(); i++) {
            TableDevice tableDevice = listDevice.get(i);
            BluetoothDevice bluetoothDevice = getBluetoothAdapter().getRemoteDevice(tableDevice.getMac());
            tableDevice.setBluetoothDevice(bluetoothDevice);
            listDevice.set(i, tableDevice);
        }
        homeLightAdapter.setNewData(listDevice);
    }

    private void getHttp() {
        //获取配置
        subscribeNoCode(Api.getApi().getDeviceConfigure("24838","1"),
                request(data -> {
                    DeviceConfigureResponse deviceConfigureResponse =(DeviceConfigureResponse)data;
                }));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void homeLightEvent(HomeLightEvent homeLightEvent) {
        getFromDataBase();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeLightColorEvent(ChangeLightColorEvent changeLightColorEvent) {
        List<TableDevice> listDevice = LitePal.findAll(TableDevice.class);
        BluetoothDevice bleDevice = changeLightColorEvent.getDevice();
        for (int i = 0; i < homeLightAdapter.getData().size(); i++) {
            if (bleDevice.getAddress().equals(homeLightAdapter.getData().get(i).getMac())) {
                homeLightAdapter.getData().get(i).setColor(changeLightColorEvent.getColor());
                homeLightAdapter.notifyItemChanged(i);
                //保存到数据库
                if (listDevice.size() == homeLightAdapter.getData().size()) {
                    TableDevice tableDevice = listDevice.get(i);
                    tableDevice.setColor(changeLightColorEvent.getColor());
                    tableDevice.save();
                } else {
                    LogUtils.e("数据库数量和界面列表不一致");
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeLightProgressEvent(ChangeLightProgressEvent changeLightProgressEvent) {
        List<TableDevice> listDevice = LitePal.findAll(TableDevice.class);
        BluetoothDevice bleDevice = changeLightProgressEvent.getDevice();
        for (int i = 0; i < listDevice.size(); i++) {
            if (bleDevice.getAddress().equals(listDevice.get(i).getMac())) {
                TableDevice tableDevice = listDevice.get(i);
                tableDevice.setBrightProgress(changeLightProgressEvent.getProgress());
                tableDevice.save();
                if (listDevice.size() == homeLightAdapter.getData().size()) {
                    homeLightAdapter.getData().get(i).setBrightProgress(changeLightProgressEvent.getProgress());
                    homeLightAdapter.notifyItemChanged(i);
                } else {
                    LogUtils.e("数据库数量和界面列表不一致");
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void removeLightEvent(RemoveLightEvent removeLightEvent) {
        LitePal.deleteAll(TableDevice.class, "mac = ? ", removeLightEvent.getMacAddress());
        for (int i = 0; i < homeLightAdapter.getData().size(); i++) {
            if (homeLightAdapter.getData().get(i).getMac().equals(removeLightEvent.getMacAddress())) {
                homeLightAdapter.getData().remove(i);
                homeLightAdapter.notifyDataSetChanged();
                break;
            }
        }
        Toast.show("灯已经被移除了");
    }

    @Override
    public void openNotify() {
        // homeLightAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onReceivedValue(String uuid, int code,String value) {
        if (code==BleManageUtils.SUCESS) {

        }
    }
}
